<template>
  <view class="page-container">
    <!-- 状态选项卡 -->
    <view class="status-tabs">
      <view 
        v-for="tab in tabs" 
        :key="tab.value"
        :class="['tab-item', activeTab === tab.value && 'active']"
        @click="onTabChange(tab.value)"
      >
        {{ tab.label }}
        <view v-if="activeTab === tab.value" class="tab-indicator"></view>
      </view>
    </view>

    <!-- 活动列表 -->
    <scroll-view class="activity-list" scroll-y>
      <view 
        v-for="activity in filteredActivities" 
        :key="activity.id"
        class="activity-card"
        :class="getCardStatusClass(activity)"
      >
        <!-- 左侧信息 -->
        <view class="left-info">
          <text class="activity-name">{{ activity.title }}</text>
          <view class="time-info">
            <uni-icons type="calendar" size="16" color="#666" />
            <text>{{ formatTime(activity.publishTime) }}</text>
          </view>
        </view>

        <!-- 右侧操作 -->
        <view class="right-action">
          <!-- 状态显示 -->
          <template v-if="activeTab === '2'">
            <view :class="['status-tag', getStatusClass(activity.reviewStatus)]">
              {{ reviewStatusMap[activity.reviewStatus] }}
            </view>
          </template>

          <!-- 操作按钮 -->
          <view class="action-buttons">
            <!-- 上架状态 -->
            <template v-if="activity.status === '1'">
              <button 
                class="action-btn offline" 
                @click="handleOffline(activity.id)"
              >
                下架
              </button>
            </template>

            <!-- 下架状态 -->
            <template v-if="activity.status === '2'">
              <button 
                class="action-btn delete" 
                @click="handleDelete(activity.id)"
              >
                删除
              </button>
<button 
  :class="['action-btn', 'online', activity.reviewStatus !== 'approved' && 'disabled']"
  :disabled="activity.reviewStatus !== 'approved'"
  @click="handleOnline(activity.id)"
>
  上架
</button>
            </template>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 发布按钮 -->
    <view class="publish-footer">
      <button class="publish-btn" @click="navigateToPublish">
        <uni-icons type="plus" size="20" color="#fff" />
        发布新活动
      </button>
    </view>
  </view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { dayjs } from '@/uni_modules/iRainna-dayjs/js_sdk/dayjs.min.js'
import request from '../../utils/request'

// 活动列表数据
const activities = ref([])

// 选项卡数据
const tabs = ref([])

// 当前选中的选项卡
const activeTab = ref('1')

// 审核状态映射
const reviewStatusMap = {
  pending: '审核中',
  approved: '审核通过',
  rejected: '审核未通过'
}

// 获取所有活动状态
const getAllActivityStatuses = async () => {
  try {
    const res = await request({
      url: `/system/dict/data/type/activity_status`,
      method: 'get',
    })
    console.log('请求成功:', res)
    if (res.code === 200 && res.data) {
      // 将字典数据转换为选项卡
      tabs.value = res.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }))
      // 默认选中第一个状态
      activeTab.value = tabs.value[0].value
      // 获取活动列表
      getActivitiesByStatus(activeTab.value)
    }
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 获取所有活动审核状态
const getAllActivityReviewStatuses = async () => {
  try {
    const res = await request({
      url: `/system/dict/data/type/activity_review`, // 假设接口路径为 activity_review
      method: 'get',
    })
    console.log('请求成功:', res)
    if (res.code === 200 && res.data) {
      // 将字典数据转换为审核状态映射
      const reviewStatusMap = res.data.reduce((map, item) => {
        map[item.dictValue] = item.dictLabel // 将 dictValue 作为键，dictLabel 作为值
        return map
      }, {})
      console.log('活动审核状态映射:', reviewStatusMap)
      return reviewStatusMap
    }
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 根据状态获取活动列表
const getActivitiesByStatus = async (status) => {
  try {
    const res = await request({
      url: `/mstore/activity/list`,
      method: 'get',
      params: {
        activityStatus: status
      }
    })
    console.log('请求成功:', res)
    // 直接将接口返回的数据赋值给 activities
    activities.value = res.map(item => ({
      id: item.activityId,
      title: item.title,
      status: item.activityStatus.toString(),
      reviewStatus: item.auditStatus === 1 ? 'approved' : 'pending',
      publishTime: item.publishTime
    }))
    console.log('赋值后的 activities:', activities.value) // 打印赋值后的活动数据
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 监听选项卡切换
const onTabChange = (value) => {
  activeTab.value = value
  getActivitiesByStatus(value)
}

// 计算属性：过滤活动列表
const filteredActivities = computed(() => {
  return activities.value.filter(item => item.status === activeTab.value)
})

// 格式化时间
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('MM/DD HH:mm')
}

// 获取卡片状态类
const getCardStatusClass = (activity) => {
  return {
    'card-pending': activity.reviewStatus === 'pending',
    'card-approved': activity.reviewStatus === 'approved',
    'card-rejected': activity.reviewStatus === 'rejected'
  }
}

// 获取状态标签类
const getStatusClass = (status) => {
  return {
    'status-pending': status === 'pending',
    'status-approved': status === 'approved',
    'status-rejected': status === 'rejected'
  }
}

// 上架活动
// 上架活动
const handleOnline = async (id) => {
  try {
    // 调用接口更新活动状态
    const res = await request({
      url: '/mstore/activity/update',
      method: 'PUT',
      data: {
        activityId: id, // 活动的唯一标识
        activityStatus: 1 // 设置为上架状态
      }
    })

    // 处理响应
    if (res.code === 200) {
      uni.showToast({ title: '上架成功' })
      // 重新获取活动列表
      getActivitiesByStatus(activeTab.value)
    } else {
      uni.showToast({ title: '上架失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('上架失败:', err)
    uni.showToast({ title: '上架失败，请重试', icon: 'none' })
  }
}

// 下架活动
const handleOffline = async (id) => {
  try {
    // 调用接口更新活动状态
    const res = await request({
      url: '/mstore/activity/update',
      method: 'PUT',
      data: {
        activityId: id, // 活动的唯一标识
        activityStatus: 2 // 设置为下架状态
      }
    })

    // 处理响应
    if (res.code === 200) {
      uni.showToast({ title: '下架成功' })
      // 重新获取活动列表
      getActivitiesByStatus(activeTab.value)
    } else {
      uni.showToast({ title: '下架失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('下架失败:', err)
    uni.showToast({ title: '下架失败，请重试', icon: 'none' })
  }
}

// 删除活动
const handleDelete = async (id) => {
  try {
    // 调用接口删除活动
    const res = await request({
      url: `/mstore/activity/delete/${id}`, // 将 activityId 作为路径参数
      method: 'DELETE', // 使用 DELETE 方法
    })

    // 处理响应
    if (res.code === 200) {
      uni.showToast({ title: '删除成功' })
      // 重新获取活动列表
      getActivitiesByStatus(activeTab.value)
    } else {
      uni.showToast({ title: '删除失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('删除失败:', err)
    uni.showToast({ title: '删除失败，请重试', icon: 'none' })
  }
}

// 跳转到发布页面
const navigateToPublish = () => {
  uni.navigateTo({ url: '/pages/event_posted_detail/event_posted_detail' })
}

// 更新活动状态
const updateActivityStatus = async (id, status) => {
  try {
    const res = await request({
      url: `/mstore/activity/updateStatus`,
      method: 'post',
      data: {
        activityId: id,
        activityStatus: status
      }
    })
    console.log('请求成功:', res)
    if (res.code === 200) {
      // 重新获取活动列表
      getActivitiesByStatus(activeTab.value)
    }
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 删除活动
const deleteActivity = async (id) => {
  try {
    const res = await request({
      url: `/mstore/activity/delete`,
      method: 'post',
      data: {
        activityId: id
      }
    })
    console.log('请求成功:', res)
    if (res.code === 200) {
      // 重新获取活动列表
      getActivitiesByStatus(activeTab.value)
    }
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 页面加载时获取活动状态和活动列表
onMounted(() => {
  getAllActivityStatuses();
  getAllActivityReviewStatuses()
})
</script>
<style lang="scss" scoped>
.page-container {
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.status-tabs {
  display: flex;
  background: #fff;
  padding: 0 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx;
    font-size: 32rpx;
    color: #666;
    position: relative;

    &.active {
      color: #007AFF;
      font-weight: 500;
    }

    .tab-indicator {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 64rpx;
      height: 4rpx;
      background: #007AFF;
      border-radius: 2rpx;
    }
  }
}

.activity-list {
  flex: 1;
  padding: 24rpx;
}

.activity-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  &.card-pending {
    border-left: 8rpx solid #FF9500;
  }
  
  &.card-approved {
    border-left: 8rpx solid #34C759;
  }
  
  &.card-rejected {
    border-left: 8rpx solid #FF3B30;
  }

  .left-info {
    flex: 1;
    padding-right: 24rpx;

    .activity-name {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 16rpx;
      display: block;
    }

    .time-info {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #666;

      text {
        margin-left: 8rpx;
      }
    }
  }

  .right-action {
    width: 240rpx;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: space-between;

    .status-tag {
      font-size: 24rpx;
      padding: 4rpx 16rpx;
      border-radius: 32rpx;

      &.status-pending {
        color: #FF9500;
        background: #FFF4E5;
      }

      &.status-approved {
        color: #34C759;
        background: #E6F4EA;
      }

      &.status-rejected {
        color: #FF3B30;
        background: #FFEBE9;
      }
    }
  }
}

.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 16rpx;
  width: 100%;

  .action-btn {
    width: 100%;
    height: 64rpx;
    line-height: 64rpx;
    border-radius: 32rpx;
    font-size: 28rpx;
    transition: all 0.2s;

    &::after {
      border: none;
    }

    &.offline, &.delete {
      background: #FF3B30; /* 红色背景 */
      color: #fff; /* 白色文字 */

      &:active {
        opacity: 0.9;
      }
    }

    &.online {
      background: #34C759; /* 绿色背景 */
      color: #fff; /* 白色文字 */

      &:active {
        opacity: 0.9;
      }

      &.disabled {
        background: #E0E0E0; /* 禁用状态灰色背景 */
        color: #999; /* 禁用状态浅灰色文字 */
        pointer-events: none;
      }
    }
  }
}

.publish-footer {
  position: sticky;
  bottom: 0;
  padding: 24rpx;
  background: linear-gradient(transparent, #f8f9fa 50%);

  .publish-btn {
    background: #007AFF;
    color: #fff;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      border: none;
    }

    &:active {
      opacity: 0.9;
    }
  }
}
</style>